package com.hssy.wululuaplan.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hssy.wululuaplan.common.ExceptionCodeEnum;
import com.hssy.wululuaplan.common.Result;
import com.hssy.wululuaplan.entity.SysUserToken;
import com.hssy.wululuaplan.exception.CustomException;
import com.hssy.wululuaplan.service.SysUserTokenService;
import com.hssy.wululuaplan.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *  登录拦截器
 */
@Slf4j
@Component
public class LoginInterceptorV2 implements HandlerInterceptor {

    @Resource
    private SysUserTokenService sysUserTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/api/login") || "/api/register".equals(requestURI)) {
            // 可记录日志
            log.info("放行登录接口: {}", requestURI);
            return true;
        }
        String token = request.getHeader("Authorization");
        log.info("=================request start===========================");
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if (token == null){
            CustomException customException = new CustomException(ExceptionCodeEnum.NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(customException));
            return false;
        }
        Map<String, Object> map = JwtUtils.checkToken(token);
        if (map == null){
            CustomException customException = new CustomException(ExceptionCodeEnum.NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(customException));
            return false;
        }
        SysUserToken sysUserToken = sysUserTokenService.getOne(Wrappers.<SysUserToken>lambdaQuery()
                .eq(SysUserToken::getToken, token)
                .last("limit 1"));
        if (sysUserToken == null){
            CustomException customException = new CustomException(ExceptionCodeEnum.NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(customException));
            return false;
        }
        if (sysUserToken.getExpireDate().getTime() < System.currentTimeMillis()){
            CustomException customException = new CustomException(ExceptionCodeEnum.LOGIN_EXPIRED);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(customException));
            return false;
        }
        return true;
    }
}